package com.zyx.xunyilu.config.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zyx.xunyilu.entity.User;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @ClassName: JWTUtils
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2019/7/27 14:22
 */
@Slf4j
@Setter
@Component
public class JWTUtils {

    @Value("${jwt.expire}")
    private long expire;

    @Value("${jwt.secret}")
    private String secret = "G5J2wXv8qlyBEKD1";

    /**
     * 生成jwt token
     */
    public String sign(String username, String password) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        try {
            return JWT.create()
                    .withIssuer("zyx")
                    // 签证时间
                    .withIssuedAt(new Date())
                    // 用户名
                    .withSubject(username)
                    // 用户密码
                    .withClaim("pwd", password)
                    // 过期时间
                    .withExpiresAt(new Date(System.currentTimeMillis() + (expire * 1000)))
                    .sign(algorithm);
        } catch (RuntimeException e) {
            log.error("签名失败! {}", e.getMessage());
            return "";
        }
    }

    public void verify(String token, String username, String password) throws JWTVerificationException {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer("zyx")
                .withSubject(username)
                .withClaim("pwd", password)
                .build();
        verifier.verify(token);
    }

    public String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getSubject();
        } catch (JWTDecodeException e) {
            log.error("解码失败! {}", e.getMessage());
            return "";
        } catch (NullPointerException e) {
            log.error("Token为空 !");
            throw new AuthorizationException();
        }
    }

    public boolean isOwner(String token, User user) {
        String username = getUsername(token);
        return (user != null && user.getName().equals(username));
    }



}
